package com.basic.business.pathRel.service.impl;

import com.basic.common.constant.CacheConstants;
import com.basic.common.constant.UserConstants;
import com.basic.common.core.redis.RedisCacheUtils;
import com.basic.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import com.basic.common.core.service.impl.BaseServiceImpl;
import com.basic.business.pathRel.domain.TPathRel;
import com.basic.business.pathRel.service.ITPathRelService;
import com.basic.business.pathRel.mapper.TPathRelMapper;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 路径关系Service业务层处理
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TPathRelServiceImpl extends BaseServiceImpl<TPathRelMapper,TPathRel> implements ITPathRelService {

    @Resource
    private TPathRelMapper tPathRelMapper;

    /**
     * 项目启动时，初始化路劲缓存
     */
    @PostConstruct
    public void init(){
        resetPathRelCache();
    }

    @Override
    public int insert(TPathRel po) {
        TPathRel tPathRel = tPathRelMapper.get(po.getParentId());
        if (tPathRel != null){
            po.setAncestors(tPathRel.getAncestors()+","+po.getParentId());
        }
        return super.insert(po);
    }

    @Override
    public int update(TPathRel po) {
        TPathRel tPathRel = tPathRelMapper.get(po.getParentId());
        if (tPathRel != null){
            // 先清空原来的
            po.setAncestors("");
            po.setAncestors(tPathRel.getAncestors()+","+po.getParentId());
        }
        return super.update(po);
    }

    @Override
    public List<TPathRel> getNormalMatPathRel() {
        return tPathRelMapper.getNormalMatPathRel();
    }

    @Override
    public void resetPathRelCache() {
        // 清空缓存
        RedisCacheUtils.clearCache(CacheConstants.PATH_REL_REDIS_KEY + "*");
        // 加载缓存
        loadingPathRelCache();
    }

    @Override
    public boolean checkPathRelNameUnique(TPathRel tPathRel) {
        String id = StringUtils.isNull(tPathRel.getId()) ? "0" : tPathRel.getId();
        TPathRel po = tPathRelMapper.checkPathRelNameUnique(tPathRel);
        if (StringUtils.isNotNull(po) && !StringUtils.equals(po.getId(), id)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int updateStatusByIds(String[] ids, String status) {
        return tPathRelMapper.updateStatusByIds(ids, status);
    }

    /**
     * 加载路径关系缓存
     */
    private void loadingPathRelCache() {

        Map<String, TPathRel> pathRelMap = getNormalMatPathRel().stream().collect(Collectors.toMap(TPathRel::getPathName, pathRel -> pathRel));
        for (Map.Entry<String, TPathRel> entry : pathRelMap.entrySet()) {
            RedisCacheUtils.setCacheObject(CacheConstants.PATH_REL_REDIS_KEY + entry.getKey(), entry.getValue());
        }

    }
}
